package demo1.demo1.controller;

import demo1.demo1.dao.DepartmentDao;
import demo1.demo1.dao.EmployeeDao;
import demo1.demo1.pojo.Department;
import demo1.demo1.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.util.Collection;

@Controller
public class IndexController {
    @RequestMapping("/user/login")
    public String login(@RequestParam("username") String username, @RequestParam String password, Model model, HttpSession session){
       if (!StringUtils.isEmpty(username) && password.equals("123456")){
           session.setAttribute("loginUser",username);
           return "redirect:/random.html";
       }
       else {
           model.addAttribute("msg","用户名或者密码错误！");
           return "index";
       }
    }
    @RequestMapping("/loginout")
    public String loginout(HttpSession session){
        session.invalidate();
        return "redirect:/index.html";
    }

    @Autowired
    EmployeeDao employeeDao;
    @Autowired
    DepartmentDao departmentDao;
    @RequestMapping("/allEmployees")
    public String employeeList(Model model){
        Collection<Employee> employees = employeeDao.getAll();
        model.addAttribute("emps",employees);
        return "abc";
    }

    @GetMapping("/addEmp")
    public  String toAddPage(Model model){
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("departments",departments);
        return "add";
    }

    @PostMapping("/addEmp")
    public  String addEmp(Employee employee){
        System.out.println(employee);
        employeeDao.save(employee);
        return "redirect:/allEmployees";
    }

    @GetMapping("/updateEmp/{id}")
    public  String toUpdatePage(@PathVariable("id")Integer id,Model model){
        Collection<Department> departments = departmentDao.getDepartments();
        Employee employee = employeeDao.getEmployeeById(id);
        model.addAttribute("departments",departments);
        model.addAttribute("emp",employee);
        return "update";
    }
    @PostMapping("/updateEmp")
    public  String updateEmp(Employee employee){
        System.out.println(employee);
        employeeDao.save(employee);
        return "redirect:/allEmployees";
    }
    @GetMapping("/deleteEmp/{id}")
    public  String DeleteEmp(@PathVariable("id")Integer id,Model model){
        employeeDao.delete(id);
        return "redirect:/allEmployees";
    }
}
